package com.inspur.edp.web.form.process.utils;


import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.bizentity.operation.BizCommonDetermination;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.collection.CommonDtmCollection;
import com.inspur.edp.cef.designtime.api.element.GspElementDataType;
import com.inspur.edp.cef.designtime.api.operation.CommonDetermination;
import com.inspur.edp.cef.designtime.api.operation.ExecutingDataStatus;
import com.inspur.edp.cef.designtime.api.variable.CommonVariable;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.bef.bizentity.common.BizEntityAtionUtil;
import com.inspur.edp.lcm.metadata.api.service.MdpkgService;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.*;

public class BEUtils {
    private static final String BEFORESAVE_COMPONENTID = "50914966-674a-43d5-9935-df726cfd51a6";
    private static final String DELETE_COMPONENTID = "d4h18e5f-4cq7-497g-b018-s41220zv145k";
    private static final String BEFORESAVE_DETERMINATION_ID = "6b3f4f6a-26f2-4199-8159-e36435c63245";
    private static final String DELETE_DETERMINATION_ID = "0e7d3731-049b-49b9-9e46-2046ef957843";

    /**
     * 添加草稿相关构件到be元数据。
     *
     * @param beMeta  需要添加构件的be元数据
     * @param canAddCmp 是否需要给be添加构件
     * @param backProjectPath 后端工程路径
     * @return 是否添加
     */
    public static boolean addDraftCmpAndSave(GspMetadata beMeta, boolean canAddCmp,String backProjectPath) {
        if (beMeta == null) {
            return false;
        }
        GspBusinessEntity be = (GspBusinessEntity) beMeta.getContent();
        if (be == null) {
            return false;
        }

        if (existDraftCmp(be) && existVariables(be)) {
            return true;
        }

        if(canAddCmp){
            addDepedency(backProjectPath);
            addActions(be);
            MetadataUtility.getInstance().saveMetadataWithDesign(beMeta);
            return true;
        }
        return false;
    }

    /**
     * 是否存在变量
     * @param be
     * @return
     */
    private static boolean existVariables(GspBusinessEntity be) {
        List<String> variables = Arrays.asList("befTaskDraftBeId","befTaskDraftProcessCategory","befTaskDraftBizCategory","befTaskDraftSummary","befTaskDraftEnableDelDtm");
        boolean isExistedVar = true;
        for(String variable:variables){
            if(!isExistedVariable(be, variable)){
                isExistedVar = false;
            }
        }
        return isExistedVar;
    }

    /**
     * 是否存在构件
     * @param be
     * @return
     */
    private static boolean existDraftCmp(GspBusinessEntity be) {
        CommonDtmCollection commonDeterminations = be.getMainObject().getDtmBeforeSave();
        boolean existSave = false;
        boolean existDelete = false;

        for (CommonDetermination commonDetermination : commonDeterminations) {
            if (BEFORESAVE_COMPONENTID.equals(commonDetermination.getComponentId())) {
                existSave = true;
            }
            if (DELETE_COMPONENTID.equals(commonDetermination.getComponentId())) {
                existDelete = true;
            }
        }
        return existSave && existDelete;
    }

    /**
     * 添加依赖
     * @param backProjectPath
     */
    private static void  addDepedency(String backProjectPath) {
        MdpkgService mdpkgService =  SpringBeanUtils.getBean(MdpkgService.class);
        List<String> metadataPackages = Arrays.asList("Inspur.Gsp.Common.CommonCmp");
        mdpkgService.addDepedencyAndRestore(backProjectPath,metadataPackages);
    }

    public static void addActions(GspBusinessEntity be) {
        addDtm(be);
        addVariables(be);
    }

    /**
     * 添加保存前事件
     * @param be
     */
    public static void addDtm(GspBusinessEntity be) {
        boolean isExistedBeforeSave = isExistedDtm(be, "50914966-674a-43d5-9935-df726cfd51a6");
        if (!isExistedBeforeSave) {
            BizCommonDetermination beforeSaveDtm = new BizCommonDetermination();
            beforeSaveDtm.setID(BEFORESAVE_DETERMINATION_ID);
            beforeSaveDtm.setCode("DraftBeforeSaveDtm");
            beforeSaveDtm.setName("DraftBeforeSaveDtm");
            beforeSaveDtm.setComponentId("50914966-674a-43d5-9935-df726cfd51a6");
            beforeSaveDtm.setComponentName("DraftBeforeSaveDetermination");
            beforeSaveDtm.setIsGenerateComponent(false);
            beforeSaveDtm.setGetExecutingDataStatus(EnumSet.of(ExecutingDataStatus.forValue(1)));
            be.getMainObject().getDtmBeforeSave().add(beforeSaveDtm);
        }

        boolean isExistedDelete = isExistedDtm(be, "d4h18e5f-4cq7-497g-b018-s41220zv145k");
        if (!isExistedDelete) {
            BizCommonDetermination deleteDtm = new BizCommonDetermination();
            deleteDtm.setID(DELETE_DETERMINATION_ID);
            deleteDtm.setCode("DraftDeleteDtm");
            deleteDtm.setName("DraftDeleteDtm");
            deleteDtm.setComponentId("d4h18e5f-4cq7-497g-b018-s41220zv145k");
            deleteDtm.setComponentName("DraftDeleteDetermination");
            deleteDtm.setGetExecutingDataStatus(EnumSet.of(ExecutingDataStatus.forValue(4)));
            deleteDtm.setIsGenerateComponent(false);
            be.getMainObject().getDtmBeforeSave().add(deleteDtm);
        }

    }

    private static CommonVariable getCommonVariable(String varCode, GspElementDataType dataType) {
        CommonVariable variable = new CommonVariable();
        variable.setID(UUID.randomUUID().toString());
        variable.setCode(varCode);
        variable.setName(varCode);
        variable.setMDataType(dataType);
        variable.setLabelID(varCode);
        variable.setLength(36);
        variable.setEnableRtrim(true);
        return variable;
    }

    /**
     * 添加变量
     * @param be
     */
    private static void addVariables(GspBusinessEntity be) {
        addVariable(be, "befTaskDraftBeId", GspElementDataType.String);
        addVariable(be, "befTaskDraftProcessCategory", GspElementDataType.String);
        addVariable(be, "befTaskDraftBizCategory", GspElementDataType.String);
        addVariable(be, "befTaskDraftSummary", GspElementDataType.String);
        addVariable(be, "befTaskDraftEnableDelDtm", GspElementDataType.Boolean);
    }

    private static void addVariable(GspBusinessEntity be, String varCode, GspElementDataType dataType) {
        boolean isExistedVar = isExistedVariable(be, varCode);
        if (!isExistedVar) {
            CommonVariable var = getCommonVariable(varCode, dataType);
            be.getVariables().getContainElements().addField(var);
        }
    }

    private static boolean isExistedVariable(GspBusinessEntity vm, String varCode) {
        boolean isExistedVariable = false;
        if (vm.getVariables().getContainElements() == null || vm.getVariables().getContainElements().size() == 0) {
            isExistedVariable = false;
            return isExistedVariable;
        }

        Iterator var3 = vm.getVariables().getContainElements().iterator();

        while(var3.hasNext()) {
            IGspCommonField variable = (IGspCommonField)var3.next();
            if (varCode.equals(variable.getCode())) {
                isExistedVariable = true;
                break;
            }
        }

        return isExistedVariable;
    }

    private static boolean isExistedDtm(GspBusinessEntity be, String componentId) {
        boolean isExist = false;
        if (be.getMainObject().getDtmBeforeSave() == null || be.getMainObject().getDtmBeforeSave().size() == 0) {
            isExist = false;
            return isExist;
        }

        Iterator var3 = be.getMainObject().getDtmBeforeSave().iterator();

        while(var3.hasNext()) {
            BizCommonDetermination action = (BizCommonDetermination)var3.next();
            if (componentId.equals(action.getComponentId())) {
                isExist = true;
                break;
            }
        }

        return isExist;
    }



}
